<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="用户名">
          <el-input v-model="listQuery.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="listQuery.realName" placeholder="请输入真实姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="listQuery.mobile" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handleSearch">查询</el-button>
          <el-button plain @click="handleReset">重置</el-button>

        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <div class="table-container-header">
        <el-button type="primary" plain @click="handleCreate">新增</el-button>
        <el-button plain type="danger" @click="removeRecord">批量删除</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        height="100%"
        style="width: 100%"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="productInventoryNumber" label="头像" width="100" align="center">
          <template slot-scope="scope">
            <img width="32" :src="scope.row.avatar"/>
          </template>
        </el-table-column>
        <el-table-column prop="userName" sortable label="用户名" width="100" />
        <el-table-column prop="realName" sortable label="姓名" width="100" />
        <el-table-column prop="gender" align="center" label="性别" width="70">
          <template slot-scope="scope">
            <span v-if="scope.row.gender===1" class="color-primary">男</span>
            <span v-if="scope.row.gender===2" class="color-success">女</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机" width="100" />
        <el-table-column prop="email" label="邮箱" width="150" />
        <el-table-column prop="idNumber" label="证件号" width="150" />
        <el-table-column prop="weixin" label="微信" width="160" />
        <el-table-column prop="isLocked" sortable label="状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.isLocked===0" class="color-primary">正常</span>
            <span v-if="scope.row.isLocked===1" class="color-danger">锁定</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150" />
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="600px"
      :before-close="handleClose"
    >

      <div>
        <el-form ref="recordForm" :model="userRecord" :rules="userRule" label-width="100px">
          <el-form-item label="所属角色" prop="roleId">
            <el-select v-model="userRecord.roleId" filterable placeholder="请选择所属角色" style="width: 100%;">
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="头像：" prop="avatar">
            <single-image-upload
              ref="avatar"
              v-model="userRecord.avatar"/>
          </el-form-item>
          <el-form-item label="账号：" prop="userName">
            <el-input v-model="userRecord.userName" placeholder="请输入账号" auto-complete="on" maxlength="20" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="真实姓名：" prop="realName">
            <el-input v-model="userRecord.realName" placeholder="请输入真实姓名" auto-complete="on" maxlength="5" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="手机：" prop="mobile">
            <el-input v-model="userRecord.mobile" placeholder="请输入手机" auto-complete="on" maxlength="11" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="userRecord.email" placeholder="请输入邮箱" auto-complete="on" maxlength="20" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="性别：" prop="gender">
            <el-radio-group v-model="userRecord.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="微信：" prop="weixin">
            <el-input v-model="userRecord.weixin" placeholder="请输入微信" auto-complete="on" maxlength="20" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="证件号：" prop="idNumber">
            <el-input v-model="userRecord.idNumber" placeholder="请输入证件号" auto-complete="on" maxlength="18" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="备注：" prop="remarks">
            <el-input v-model="userRecord.remarks" type="textarea" placeholder="请输入备注" maxlength="200" show-word-limit clearable />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialog.status == 'updated'?updateData():createData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      multipleSelectionRecords: [],
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        userName: '',
        realName: '',
        mobile: '',
        sort: '+gmtModified'
      },
      dialog: {
        title: '新增商品分类',
        status: 'created',
        visible: false
      },
      roles: [],
      userRecord: {

      },

      userRule: {
        roleId: [
          { required: true, message: '请选择用户角色', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请正确输入手机号', trigger: 'blur' }
        ]

      }
    }
  },
  created() {
    this.fetchData()
    this.fetchRole()
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    fetchRole() {
      this.$store.dispatch('roleList').then((res) => {
        this.roles = res
      }).catch((_) => {})
    },
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '+gmtModified'
      }
      this.handleSearch()
    },
    fetchData() {
      this.$store.dispatch('userPage', this.listQuery).then((res) => {
        this.list = res.records
        this.total = res.total
      }).catch((_) => {})
    },
    handleSearch() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: 20,
        userName: '',
        realName: '',
        mobile: '',
        sort: '+gmtModified'
      }
      this.fetchData()
    },
    handleCreate() {
      this.userRecord = {
        gender: 1
      }
      this.dialog = {
        visible: true,
        status: 'created',
        title: '新增用户'
      }
      this.$nextTick(() => {
        this.$refs.recordForm.clearValidate()
      })
    },
    createData() {
      this.$refs.recordForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch('userSave', this.userRecord).then((res) => {
            this.$message.success('添加成功！')
            this.dialog = {
              visible: false
            }
            this.handleReset()
          }).catch((_) => {})
        } else {
          return false
        }
      })
    },
    handleUpdate(row) {
      this.userRecord = Object.assign({}, row)
      this.dialog = {
        visible: true,
        status: 'updated',
        title: '编辑用户'
      }
      this.$nextTick(() => {
        this.$refs.recordForm.clearValidate()
      })
    },
    updateData() {
      this.$refs.recordForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch('userUpdate', this.userRecord).then((res) => {
            this.$message.success('修改成功！')
            this.dialog = {
              visible: false
            }
            this.handleReset()
          }).catch((_) => {})
        } else {
          return false
        }
      })
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('userRemove', ids).then(response => {
            this.handleReset()
            this.$message.success('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$message.warning('请选择要删除的记录')
      }
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
